package com.dianban.controller.nengliang;

import com.dianban.base.ResultCode;
import com.dianban.base.ResultVo;
import com.dianban.config.redis.RedisConstant;
import com.dianban.config.redis.RedisUtil;
import com.dianban.controller.BaseController;
import com.dianban.entity.JwShoproArea;
import com.dianban.entity.User;
import com.dianban.service.JwShoproAreaService;
import com.dianban.utils.UserUtils;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiImplicitParam;
import io.swagger.annotations.ApiImplicitParams;
import io.swagger.annotations.ApiOperation;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.util.ArrayList;
import java.util.List;

@Api(value = "ApiAreaController", description = "地址选择控制器")
@RestController
@RequestMapping(value = "${interfacePath}/nengliang/area/")
public class ApiAreaController extends BaseController {

    @Autowired
    private JwShoproAreaService jwShoproAreaService;

    @ApiOperation(notes = "list", httpMethod = "GET", value = "获取所有地址")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "userToken", value = "用户token", required = true, paramType = "header", dataType = "string"),
            @ApiImplicitParam(name = "pid", value = "上级id", required = false, paramType = "query", dataType = "string"),
    })
    @RequestMapping(value = "list", method = RequestMethod.GET)
    public ResultVo areaList(@RequestParam(value = "pid", required = false, defaultValue = "0") String pid, HttpServletRequest request, HttpServletResponse response) {
        String userToken = request.getHeader(UserUtils.USER_TOKEN);
        String key = RedisConstant.USER_TOKEN_KEY + userToken;
        User user = (User) RedisUtil.get(key);
        if (user == null) {
            return ResultVo.error(ResultCode.ERROR, "请求头userToken过期");
        }
        List<JwShoproArea> areaList = new ArrayList<>();
        try {
            areaList = jwShoproAreaService.findList(pid);
        } catch (Throwable e) {
            e.printStackTrace();
            return ResultVo.error(ResultCode.ERROR, "获取失败");
        }
        return ResultVo.success(areaList, "获取成功");
    }

}
